package com.ctbri.vSearch.dao;


import com.ctbri.vSearch.bean.proto.ArticleItemProto;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import redis.clients.jedis.Jedis;

/**
 * Created by xuexi on 2017/5/3.
 */
public class ES2Redis {

    public static Long cntArticle = 1L;  //如何回归初始值问题待优化，spring貌似只有一个ES2Redis实例，这里不希望这样
    public void createES2RedisByWord(String word, Jedis client){
        client.set(word+"_ES","0");
        client.expire(word,60*30); //1800s失效时间
    }
    public void putArticle2Redis(String id, String content, String official_account, String title,
            String url, String date, String time, float score, Jedis client, String word)
            throws IOException {
        ArticleItemProto.ArticleItem.Builder articleBuilder =  ArticleItemProto.ArticleItem.newBuilder();
        articleBuilder.setId(id);
        articleBuilder.setContent(content);
        if(official_account!=null){
            articleBuilder.setOffcialAccount(official_account);
        }
        articleBuilder.setTitle(title);
        articleBuilder.setUrl(url);
        if(date!=null){
            articleBuilder.setDate(date);
        }
        if(time!=null){
            articleBuilder.setTime(time);
        }
        Float f = new Float(score);
        articleBuilder.setScore(f.toString());
        ArticleItemProto.ArticleItem articleB = articleBuilder.build();
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        articleB.writeTo(output);
        byte[] byteArray = output.toByteArray();
        String s =new String(byteArray,"ISO-8859-1");
        HashMap<String, String> map = new HashMap<>();
        map.put(cntArticle.toString(),s);
        client.hmset(word+"_article_ES", map);  //可优化为List
        System.out.println("已将"+word+"的ES查询结构存入redis,ArticleId:"+cntArticle);
        cntArticle++;

    }

}
